package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.sky.constant.MessageConstant;
import com.sky.dto.UserLoginDTO;
import com.sky.entity.User;
import com.sky.mapper.UserMappper;
import com.sky.properties.WeChatProperties;
import com.sky.service.UserService;
import com.sky.utils.HttpClientUtil;
import org.apache.ibatis.logging.LogException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.HashMap;

@Service
public class UserServiceimpl implements UserService {
    @Autowired
    private WeChatProperties  weChatProperties;
    @Autowired
    private UserMappper  userMappper;

    // 微信服务接口地址
    public static final String wx_Login = "https://api.weixin.qq.com/sns/jscode2session";
    /**
     * 微信登录
     * @param userLoginDTO
     * @return
     */
    @Override
    public User login(UserLoginDTO userLoginDTO) {
        String openid = getOpenid(userLoginDTO.getCode());
        //判断open-id是否为空
        if(openid == null){
            throw new LogException(MessageConstant.LOGIN_FAILED);
        }
        //判断是否为新用户
        User user = userMappper.getUserByOpenid(openid);
        //如果是新用户，自动注册
        if(user == null){
            user = User.builder()
                    .openid(openid)
                    .createTime(LocalDateTime.now())
                    .build();
            userMappper.insert(user);
        }
        //返回用户信息
        return user;
    }

    /**封装
     * 调用微信接口服务，获得当期微信用户的openid
     * @param code
     * @return
     */
    private String getOpenid(String code) {
        //调用微信接口服务，获得当期微信用户的openid
        HashMap<String, String> map = new HashMap<>();
        map.put("appid", weChatProperties.getAppid());
        map.put("secret", weChatProperties.getSecret());
        map.put("js_code",code);
        String json = HttpClientUtil.doGet(wx_Login, map);
        JSONObject object = JSON.parseObject(json);
        String openid = object.getString("openid");
        return openid;
    }
}
